<?php
namespace app\common\tool;

class Curl {
	protected $headers = ['Content-Type: application/x-www-form-urlencoded'];

	public function curl($fun) {
		$ch = curl_init();
        // 将数组形式的 POST 数据转换为 URL 编码的字符串
        if($fun) {
        	$fun($ch);
    	}
        // 将响应结果以字符串形式返回而不是直接输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 设置请求头，指定内容类型为表单数据
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
        // 执行 cURL 请求
        $response = curl_exec($ch);
        // 检查是否有错误发生
        if (curl_errno($ch)) {
        	throw new \Exception('Curl 错误: '. curl_error($ch));
        }
        // 获取 HTTP 响应状态码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // 关闭 cURL 会话
        curl_close($ch);
        return $response;
	}

	public function set_headers($headers) {
		$this->headers = $headers;
		return $this;
	}

	public function get($url) {
		return $this->curl(function($ch) use ($url){
	        // 设置请求的 URL
	        curl_setopt($ch, CURLOPT_URL, $url);
		});
	}

	public function post($url, $data, $type = 'http_build_query') {
		$data = $type($data);
		return $this->curl(function($ch) use ($url, $data){
			// 设置请求的 URL
	        curl_setopt($ch, CURLOPT_URL, $url);
	        // 启用 POST 请求
	        curl_setopt($ch, CURLOPT_POST, 1);
	        // 设置 POST 数据
	        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		});
	}

	public function body($url, $data, $type = 'http_build_query') {
		$data = $type($data);
		return $this->curl(function($ch) use ($url, $data){
			// 设置请求的 URL
			curl_setopt($ch, CURLOPT_URL, $url);
	        
	        // 启用 POST 请求
	        curl_setopt($ch, CURLOPT_POST, 1);

	        $this->headers = ['Content-Type: application/json'];

	        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	        
		});
	}

	public function jisongbang($url, $data) {
		$ch = curl_init();

		curl_setopt_array($ch, [
		    CURLOPT_URL => $url,
		    CURLOPT_POST => true,
		    CURLOPT_POSTFIELDS => $data, // 直接传递纯文本字符串
		    CURLOPT_HTTPHEADER => [
		        "Content-Type: text/plain", // 声明数据格式为纯文本
		    ],
		    CURLOPT_RETURNTRANSFER => true,
		]);

		$response = curl_exec($ch);

		if (curl_errno($ch)) {
        	throw new \Exception('Curl 错误: '. curl_error($ch));
        }
        // 获取 HTTP 响应状态码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // 关闭 cURL 会话
        curl_close($ch);
        $response = json_decode($response, true);
        if(!isset($response['code']) || $response['code'] != 200) {
        	throw new \Exception($response['msg']);
        }
        return $response['data'];
	}
}